package at.ac.tuwien.swa.sparrow.conf

import akka.actor.{ActorRef, ActorSystem}
import at.ac.tuwien.swa.sparrow.common.Account
import at.ac.tuwien.swa.sparrow.peer.component.MusicLibrary
import at.ac.tuwien.swa.sparrow.peer.{PeerActor, PeerActorFactory}
import at.ac.tuwien.swa.sparrow.server.PeerService
import at.ac.tuwien.swa.sparrow.server.persistence.AccountRepository
import com.typesafe.config.{Config, ConfigValueFactory, ConfigFactory}
import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject
import org.springframework.context.annotation.{Configuration, Bean, FilterType, ComponentScan}
import scala.collection.JavaConverters._

object SpringTestConfig {
	val config = (ConfigFactory load "reference" getConfig "swazam")
		.withValue("library.paths", ConfigValueFactory fromIterable List("/tmp/lib").asJava)
		.withValue("password", ConfigValueFactory fromAnyRef "secret")
}

@Configuration
@ComponentScan(value = Array("at.ac.tuwien.swa"),
	excludeFilters = Array(
		new ComponentScan.Filter(`type` = FilterType.ANNOTATION, value = Array(classOf[Configuration])),
		new ComponentScan.Filter(`type` = FilterType.ASSIGNABLE_TYPE, value = Array(classOf[AccountRepository]))
	))
class SpringTestConfig {

	val system = ActorSystem("AkkaScalaSpring")
	@Inject var peerActorFactory: PeerActorFactory = _

	@Bean def actorSystem = system

	@Bean def firstPeer: ActorRef = {
		peerActorFactory.actorType = classOf[TestablePeerActor]
		peerActorFactory.config = config withValue("username", ConfigValueFactory fromAnyRef "demo1")
		peerActorFactory.createInstance
	}

	@Bean def config = {
		SpringTestConfig.config withValue("username", ConfigValueFactory.fromAnyRef("demo1"))
	}

	@Bean def accountRepository() = {
		val accountRepository = new AccountRepository()
		accountRepository.save(Account("demo1", "secret", new AtomicLong(100)))
		accountRepository.save(Account("demo2", "secret", new AtomicLong(100)))
		accountRepository
	}
}

class TestablePeerActor @Inject()(peerService: PeerService, library: MusicLibrary, config: Config)
	extends PeerActor(peerService, library, config) {

	override def saveConfiguration() {}
}
